package com.imooc.bilibili.service;

import com.imooc.bilibili.domain.auth.*;
//import com.imooc.bilibili.domain.constant.AuthRoleConstant;
import com.imooc.bilibili.domain.constant.AuthRoleConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserAuthService {

    //引入用户角色绑定的依赖
    @Autowired
    private UserRoleService userRoleService;
   //拿到用户角色，知道绑定了哪些权限
    @Autowired
    private AuthRoleService authRoleService;

    public void addUserDefaultRole(Long id) {
       UserRole userRole = new UserRole();
       AuthRole role = authRoleService.getRoleByCode(AuthRoleConstant.ROLE_LV0);
       userRole.setUserId(role.getId());
       userRole.setRoleId(role.getId());
       userRoleService.addUserRole(userRole);

    }

    //获取用户的角色，是一对多的
    public UserAuthorities getUserAuthorities(Long userId) {
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);  //每次新表都要在xml文件中重写
        //获取到角色id
        Set<Long> roleIdSet = userRoleList.stream().map(UserRole :: getRoleId).collect(Collectors.toSet());
        //获取页面元素的操作权限，按钮的操作权限
        List<AuthRoleElementOperation> roleElementOperationList = authRoleService.getRoleElementOperationsByRoleIds(roleIdSet);
        List<AuthRoleMenu> authRoleMenuList = authRoleService.getAuthRoleMenusByRoleIds(roleIdSet);
        UserAuthorities userAuthorities = new UserAuthorities();
        userAuthorities.setRoleElementOperationList(roleElementOperationList);
        userAuthorities.setRoleMenuList(authRoleMenuList);
        return userAuthorities;
    }

//    public void addUserDefaultRole(Long id) {
//        UserRole userRole = new UserRole();
//        AuthRole role = authRoleService.getRoleByCode(AuthRoleConstant.ROLE_LV0);
//        userRole.setUserId(id);
//        userRole.setRoleId(role.getId());
//        userRoleService.addUserRole(userRole);
//    }
}
